package com.ol.edu.server.controller.Authority;

import com.github.pagehelper.PageInfo;
import com.ol.edu.server.entity.Menu;
import com.ol.edu.server.entity.ResponseResult;
import com.ol.edu.server.service.Authority.MenuService;
import com.ol.edu.server.service.Authority.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Roger
 * @date 2020/9/9 6:37
 * @description
 */
@RestController
@RequestMapping("/menu")
@CrossOrigin
public class MenuController {
    @Autowired
    private MenuService menuService;
    /*
        查询菜单列表
     */
    @RequestMapping("/findAllMenu")
    public ResponseResult findAllMenu(Integer currentPage, Integer pageSize) {
        PageInfo<Menu> pageInfo = menuService.findAllMenu(currentPage, pageSize);
        return new ResponseResult(true, 200, "菜单列表查询成功", pageInfo);
    }

    @Autowired
    private RoleService roleService;
    /*
        根据菜单ID 查询菜单信息
        如果是新增菜单,则id值为 -1, 修改菜单 则为当前选择的id值
     */
    @RequestMapping("/findMenuInfoById")
    public ResponseResult findMenuInfoById(Integer id) {
        //封装数据传给前端
        Map<String, Object> map = new HashMap<>(2);
        List<Menu> allMenu = roleService.findAllMenu();
        //新增操作
        if (id == -1) {
            map.put("menuInfo", null);
            map.put("parentMenuList", allMenu);
            return new ResponseResult(true, 200, "查询菜单信息成功", map);
        } else {
            Menu menu = menuService.getMenuInfoById(id);
            map.put("menuInfo", menu);
            map.put("parentMenuList", allMenu);
            return new ResponseResult(true, 200, "查询菜单信息成功", map);
        }
    }
    /*
        保存和修改菜单
     */
    @RequestMapping("/saveOrUpdateMenu")
    public ResponseResult saveOrUpdateMenu(@RequestBody Menu menu) {
        // 如果传入ID为空表示是新增
        if (menu.getId() == null) {
            menuService.saveMenu(menu);
            return new ResponseResult(true, 200, "添加菜单成功", null);
        } else {// 更新
            menuService.updateMenu(menu);
            return new ResponseResult(true, 200, "修改菜单成功", null);
        }
    }

    @RequestMapping("/deleteMenu")
    public ResponseResult deleteMenu(Integer id) {
        menuService.deleteMenu(id);
        return new ResponseResult(true, 200, "删除成功", null);
    }

}
